import Koa from "koa";
import cors from "@koa/cors";
import webSocketHelper from "./utils/socketHelper";
import http from "http";
import path from "path";
import serve from "koa-static";

import connection,{ init_connection } from "./router/connection";
import videoRouter from "./router/video";
import get_static from "./router/get_static";
 

const app = new Koa();

const port = 3035;

// 创建 HTTP 服务器
const server = http.createServer(app.callback());

// 更新 CORS 配置
app.use(
  cors({
    origin: "*",
    methods: ["GET", "POST"],
    credentials: true,
  })
);

const publicPath = "./public";

// 使用 koa-static 中间件
app.use(serve(publicPath));

// 全局注入
app.context.error = function (message: string, code: number = 500) {
  this.body = { message, code };
};
app.use(connection.routes());
app.use(videoRouter.routes());
app.use(get_static.routes());

// 初始化 WebSocket 服务器
webSocketHelper.server = server; // 设置 server 实例
init_connection(); // 调用初始化函数

// 启动服务器
server.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});